var express = require('express')
var router = express.Router()
const { getAll, getOne, exec } = require('../db')
var jwt = require('jsonwebtoken')

const secretKey = 'secret'
// 1.PC端用户登录
///users/login username password
router.post('/', async function (req, res, next) {
  const { username, password } = req.body
  let sql1 = `select * from gg_user where user_username='${username}' and user_password='${password}'`
  const data = await getOne(sql1)
  console.log(data)
  // 登录成功, 生成token返回给客户端
  if (data) {
    // console.log(data)
    const user_type = data.user_type
    const use_id = data.use_id
    const user_onlinestatus = data.user_onlinestatus
    const user_truename = data.use_truename
    const user_tel = data.user_tel
    const user_existstatus = data.user_existstatus

    if (data.user_type == '管理员' || data.user_type == '交通部门') {
      const token = jwt.sign({ username, password }, secretKey, {
        expiresIn: '24h',
      })
      res.send({
        code: 0,
        message: '登录成功',
        result: {
          token,
          user_type,
          use_id,
          user_onlinestatus,
          user_existstatus,
        },
      })
    } else {
      // 普通用户
      // 获取token签名
      const token = jwt.sign({ username, password }, secretKey, {
        expiresIn: '7d',
      })
      const user_type = data.user_type
      const use_id = data.use_id
      const user_onlinestatus = data.user_onlinestatus
      const user_existstatus = data.user_existstatus
      res.send({
        code: 10000,
        message: '移动端:普通用户登录成功---Web端:没有权限',
        result: {
          token,
          user_type,
          use_id,
          user_username: username,
          user_truename,
          user_tel,
          user_onlinestatus,
          user_existstatus,
        },
      })
    }
  } else {
    res.send({
      code: 10001,
      message: '用户名或者密码错误',
      result: '',
    })
  }
})

module.exports = router
